package org.softmed.rest.server.core.restlet;

import java.util.List;

import org.softmed.rest.config.Application;
import org.softmed.rest.config.Handler;
import org.softmed.rest.config.HttpMethod;
import org.softmed.rest.config.MimeTypeHandler;
import org.softmed.rest.config.Module;
import org.softmed.rest.config.Parameter;
import org.softmed.rest.config.Resource;
import org.softmed.rest.server.core.boot.ApplicationProvider;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class RESTConfigRefresher {

	static ResourceSetup resourceSetup = new ResourceSetup();

	@Inject
	static ApplicationProvider configuration;

	@Inject
	static RESTServer server;

	@Inject
	@Named("StoredRESTContextName")
	static String storedRESTContextName;

	public synchronized static void refreshConfig(Object object)
			throws Throwable {
		if (!isRESTConfigObject(object))
			return;

		refreshConfig();

	}

	public static void removeAllDeployedResources() {
		server.getApplication().removeAllResources();
	}

	public static void refreshConfig() {
		try {
			List<Application> apps = configuration.getApplications();

			server.getApplication().removeAllResources(storedRESTContextName);

			resourceSetup.setServer(server);
			resourceSetup.setContextName(storedRESTContextName);

			if (apps != null)
				for (Application app : apps) {
					resourceSetup.setupApp(app);
				}

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private static boolean isRESTConfigObject(Object object) {

		if (object instanceof Application)
			return true;

		if (object instanceof Module)
			return true;

		if (object instanceof Resource)
			return true;

		if (object instanceof HttpMethod)
			return true;

		if (object instanceof MimeTypeHandler)
			return true;

		if (object instanceof Handler)
			return true;

		if (object instanceof Parameter)
			return true;

		return false;

	}

	public static RESTServer getServer() {
		return server;
	}

}
